//
//  MRHttpTool.m
//  MReader
//
//  Created by Qi Liu on 2020/4/5.
//  Copyright © 2020 Qi Liu. All rights reserved.
//

#import "BLHttpTool.h"
#import "BLNetManager.h"

@implementation BLHttpTool
+(void) getHttpRequest:(NSString *)urlpath param:(NSDictionary *)params finish:( void (^)(NSURLSessionDataTask *data,NSDictionary *obj))successBlock failedBlock:(void (^)(id  data, NSError *error))failedBlock{
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    
    BLNetManager * netManager = [BLNetManager sharedHttpManager];
    [self doCookiesWtihManager:netManager];

    [netManager GET:urlpath parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task , id _Nullable obj) {

        if (obj && [obj isKindOfClass:[NSDictionary class]]) {
            if ([obj[@"code"] integerValue] == 1) {
                successBlock(task,obj);
                return ;
            }else if ([obj[@"code"] integerValue] == -1) {
                [BLUserManager shareUser].userInfo = nil;
                NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
                [prefs removeObjectForKey:K_Login_Ppu];
                [prefs removeObjectForKey:K_Login_RegisterStep];
                [prefs synchronize];
                [[NSNotificationCenter defaultCenter] postNotificationName:Notification_login object:nil];

            }else{
                [HUD showtip:obj[@"msg"]];
            }
        }
        failedBlock(task,obj);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failedBlock(task,error);
    }];

    
//    [netManager GET:urlpath parameters:params progress:nil success:successBlock failure:failedBlock];

}

+ (void)postWithPath:(NSString *)path
              params:(NSDictionary *)params
        successBlock:(void (^)(NSDictionary *obj))successBlock
         failedBlock:(void(^)(NSURLSessionDataTask *data,NSError *error))failedBlock{
    BLNetManager * netManager = [BLNetManager sharedHttpManager];
    [self doCookiesWtihManager:netManager];
    
    [netManager POST:path parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable obj) {
        if (obj && [obj isKindOfClass:[NSDictionary class]]) {
            if ([obj[@"code"] integerValue] == 1) {
                successBlock(obj);
                return ;
            }else if ([obj[@"code"] integerValue] == -1) {
                [BLUserManager shareUser].userInfo = nil;
                NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
                [prefs removeObjectForKey:K_Login_Ppu];
                [prefs removeObjectForKey:K_Login_RegisterStep];
                [prefs synchronize];
                [[NSNotificationCenter defaultCenter] postNotificationName:Notification_login object:nil];
            }else{
                [HUD showtip:obj[@"msg"]];
            }
        }
        failedBlock(task,obj);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failedBlock(task,error);
    }];
}

+(void)doCookiesWtihManager:(BLNetManager *)manager{
    // 如果已有Cookie, 则把你的cookie符上
    NSString *cookie = [[NSUserDefaults standardUserDefaults] objectForKey:COOKIES_KEY];
    if (cookie != nil) {
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    if ([BLUserManager shareUser].userPpu &&[BLUserManager shareUser].userPpu.length>0 ) {
        [manager.requestSerializer setValue:[BLUserManager shareUser].userPpu forHTTPHeaderField:@"ppu"];
    }
//

    
}


+(NSURLSessionDownloadTask *)downloadWithUrl:(NSString *)urlStr
                                    progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                                 destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                           completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler{
    BLNetManager * netManager = [BLNetManager sharedHttpManager];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *downloadTask =   [netManager downloadTaskWithRequest:request progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
    [downloadTask resume];
    return downloadTask;
}



+ (NSString *)arrayToJSONString:(NSArray *)array

 {
    NSError *error = nil;
//    NSMutableArray *muArray = [NSMutableArray array];
//    for (NSString *userId in array) {
//        [muArray addObject:[NSString stringWithFormat:@"\"%@\"", userId]];
//    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
//    NSLog(@"json array is: %@", jsonResult);
    return jsonString;
}

+(void)postJson:(NSString*)url params:(NSDictionary *)params  successBlock:(void (^)(NSDictionary *obj))successBlock failedBlock:(void(^)(NSError *error))failedBlock{
    // 请求头
    NSString *accessPath = [NSString stringWithFormat:@"%@/%@",BL_BASEURL,url];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
   __block NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:accessPath parameters:params error:nil];
    request.timeoutInterval = 10.f;
    
    NSMutableDictionary * headerParams = [NSMutableDictionary dictionaryWithDictionary:params];
    [headerParams setValue:BL_STRING([BLUserManager shareUser].userPpu) forKey:@"ppu"];
    [headerParams enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        
        NSString * arrayString = @"";
        if ([obj isKindOfClass:[NSArray class]]) {
            arrayString = [self arrayToJSONString:obj];
        }else{
            arrayString = [NSString stringWithFormat:@"%@",obj];
        }
        
        [request setValue:arrayString forHTTPHeaderField:[NSString stringWithFormat:@"%@",key]];
    }];
        
    NSURLSessionDataTask *task =  [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            
            if (responseObject && [responseObject isKindOfClass:[NSDictionary class]]) {
                if ([responseObject[@"code"] integerValue] == 1) {
                    successBlock(responseObject);
                    return ;
                }else if ([responseObject[@"code"] integerValue] == -1) {
                    [BLUserManager shareUser].userInfo = nil;
                    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
                    [prefs removeObjectForKey:K_Login_Ppu];
                    [prefs removeObjectForKey:K_Login_RegisterStep];
                    [prefs synchronize];
                }else{
                    [HUD showtip:responseObject[@"msg"]];
                }
            }else {
                failedBlock(error);
            }
        } else {
            failedBlock(error);
            NSLog(@"请求失败error=%@", error);
        }
    }];
    [task resume];
}



-(void)clearCookies{
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:COOKIES_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
